package cn.tedu.v1_1;
/**
 * 聊天室 version1.1
 * 服务器  功能：1.服务器申请端口号：软件具备端口号
 *             2.在start方法中：等待客户端连接，返回socket
 *               IO读入
 *          【新增】3.所有服务器端异常全部捕获，明确提示什么原因造成
 *             4.关闭serverSocket
 *
 */

import java.io.*;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

public class Server {
    private ServerSocket serverSocket;
    public Server() {
        try {
            serverSocket = new ServerSocket(1117);
        }catch (BindException e){
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start() {
        BufferedReader br = null;
        Socket socket = null;
        try {
            System.out.println("等待客户端的连接");
            socket = serverSocket.accept();
            System.out.println("一个客户端连接上了");
            InputStream is = null;
            //OutputStream os=null;
            InputStreamReader isr = null;
            //OutputStreamWriter osw=null;
            // BufferedReader br = null;
            // BufferedWriter bw=null;

            is = socket.getInputStream();
            //os=socket.getOutputStream();

            isr = new InputStreamReader(is, "UTF8");
            // osw=new OutputStreamWriter(os);

            br = new BufferedReader(isr);
            //bw=new BufferedWriter(osw);
            while (true) {
                String str = br.readLine();
                System.out.println("客户端：" + str);
            }
        } catch (UnsupportedEncodingException e){
            System.out.println("服务器端与客户端连接不一致");
        }catch (SocketException e){
            System.out.println("");
        }
        catch (IOException e) {
            System.out.println("服务器端断开连接");
        } finally {
            if (br!=null)
                try {
                    br.close();
                } catch (IOException e) {
                    System.out.println();
                }
            try {
                socket.close();
            } catch (IOException e) {
                System.out.println();
            }
        }
    }
    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }
}
